﻿using AutoMapper;
using MediatR;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PigArchives
{
    /// <summary>
    /// 基本信息添加handler
    /// </summary>
    public class AddBasicHandler : IRequestHandler<AddBasicCommand, Result>
    {
        /// <summary>
        /// AutoMapper
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 猪只基本信息
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationrepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<AddBasicHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper">mapper</param>
        /// <param name="basicInformationrepository">basicInformationrepository</param>
        /// <param name="logger">logger</param>
        public AddBasicHandler(IMapper mapper, 
            IBaseRepository<BasicInformation> basicInformationrepository, 
            ILogger<AddBasicHandler> logger)
        {
            this.mapper = mapper;
            this.basicInformationrepository = basicInformationrepository;
            _logger = logger;
        }
        /// <summary>
        /// 猪只基本信息添加
        /// </summary>
        /// <param name="request">request</param>
        /// <param name="cancellationToken">cancellationToken</param>
        /// <returns></returns>
        public async Task<Result> Handle(AddBasicCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                BasicInformation basicInformation = mapper.Map<BasicInformation>(request);
                var res = await basicInformationrepository.Add(basicInformation);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                }
                result.Msg = "基本信息添加成功";
            }
            catch (Exception ex)
            {
                _logger.LogError("基本信息添加失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
